<template>
  <div>
    <!-- 内容主体区域 -->
    <dtDialog
      title="分配菜单"
      :visible.sync="visible"
      :is-loading="loading"
      @closeDialog="handleClose()"
      @comfirmBtn="onSubmit()"
    >
      <el-form ref="form" slot="content" :model="formData" label-width="100px">
        <div style="margin-bottom:10px">
          <el-button @click="allSelect">全选</el-button>
          <el-button @click="reset">清空</el-button>
        </div>
        <el-input
          v-model="filterText"
          placeholder="输入按钮或菜单名称进行搜索"
          style="margin-bottom:10px;"
        />
        <el-tree
          ref="tree"
          class="tree"
          :filter-node-method="filterNode"
          :data="roleAssignMenuTree"
          :props="defaultProps"
          show-checkbox
          node-key="id"
          check-on-click-node
          :expand-on-click-node="false"
          @check="handleNodeCheck"
        />
      </el-form>
    </dtDialog>
  </div>
</template>

<script>
import api from '@/framework/api/role'
export default {
  name: 'RoleAssignMenu',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    formData: {
      type: Object,
      default: () => { return {} }
    },
    closeForm: {
      type: Function,
      default: function() {}
    }
  },
  data() {
    return {
      loading: false,
      filterText: '',
      grantMenuIdList: [],
      grantMenuButtonIdList: [],
      roleAssignMenuTree: [],
      defaultProps: {
        id: 'id',
        children: 'children',
        label: 'name'
      }
    }
  },
  // created() {
  //   this.getMenuAndButton()
  // },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val)
    }
  },
  methods: {
    // 获取数据范围列表
    async getMenuAndButton(id) {
      let listObj = []
      // let list = []
      const res = await api.menuAndButtonTree(id)
      this.roleAssignMenuTree = res.data
      // list = this.resolveAllEunuchNodeId(this.roleAssignMenuTree, [])
      listObj = this.resolveAllEunuchNodeId(this.roleAssignMenuTree, [])
      const btnList = []
      const menuList = []
      const allList = []
      listObj.forEach(item => {
        if (item.buttonCode) {
          btnList.push({
            buttonCode: item.buttonCode,
            buttonId: item.id
          })
        } else {
          menuList.push(item.id)
        }
        allList.push(item.id)
      })

      this.grantMenuIdList = menuList
      this.grantMenuButtonIdList = btnList
      // this.$nextTick(() => {
      //   this.$refs.tree.setCheckedKeys(allList)
      // })
      this.$nextTick(() => {
        if (this.$refs.tree) {
          // this.$refs.tree.setCheckedNodes(this.checkedKeys)
          const nodes = []
          allList.forEach(item => {
            const node = this.$refs.tree.getNode(item)
            if (node && node.isLeaf) { // 关键，过滤掉不是叶子节点的
              nodes.push(item)
            }
          })
          this.$refs.tree.setCheckedKeys(nodes, true)
        }
      })
    },
    /**
       * 解析出所有的太监节点id
       * @param idArr 原始节点数组
       * @param temp 临时存放节点id的数组
       * @return 太监节点id数组
       */
    resolveAllEunuchNodeId(idArr, temp) {
      for (let i = 0; i < idArr.length; i++) {
        const item = idArr[i]
        // 存在子节点，递归遍历;不存在子节点，将json的id添加到临时数组中
        if (item.children && item.children.length !== 0) {
          // if (item.checked) {
          //   temp.push(item)
          // }
          this.resolveAllEunuchNodeId(item.children, temp)
        }
        if (item.checked) {
          temp.push({ ...item, children: [] })
        }
      }
      return temp
    },
    handleNodeCheck(data) {
      const list = []
      const buttonlist = []
      const halfCheckedList = []
      const halfCheckedButtonList = []
      const orgList = this.$refs['tree'].getCheckedNodes()
      for (let i = 0; i < orgList.length; i++) {
        if (orgList[i].menuFlag) {
          list.push(orgList[i].id)
        } else {
          buttonlist.push({
            'buttonId': orgList[i].id,
            'buttonCode': orgList[i].buttonCode
          })
        }
      }
      const halfCheckedNodesList = this.$refs['tree'].getHalfCheckedNodes()
      for (let i = 0; i < halfCheckedNodesList.length; i++) {
        if (halfCheckedNodesList[i].menuFlag) {
          halfCheckedList.push(halfCheckedNodesList[i].id)
        } else {
          halfCheckedButtonList.push({
            'buttonId': halfCheckedNodesList[i].id,
            'buttonCode': halfCheckedNodesList[i].buttonCode
          })
        }
      }
      this.grantMenuIdList = [...list, ...halfCheckedList]

      this.grantMenuButtonIdList = [...buttonlist, ...halfCheckedButtonList]
    },
    // 关闭对话框触发
    handleClose() {
      // 清空数据关闭页面
      this.$refs['form'].resetFields()
      this.filterText = ''
      this.$nextTick(() => {
        // this.$refs.tree.setCheckedKeys([])
      })
      this.closeForm()
    },
    async onSubmit() {
      this.loading = true
      const data = {
        'grantMenuButtonIdList': this.grantMenuButtonIdList,
        'grantMenuIdList': this.grantMenuIdList,
        'roleId': this.formData.roleId
      }
      try {
        const res = await api.grantMenuAndButton(data)
        if (res.code === '00000') {
          this.$message({
            type: 'success',
            message: '分配成功'
          })
          this.handleClose()
        } else {
          this.$message({
            type: 'error',
            message: '分配失败'
          })
        }
        this.loading = false
      } catch (error) {
        this.loading = false
      }
    },
    allSelect() {
      this.$refs.tree.setCheckedNodes(this.roleAssignMenuTree)
      this.handleNodeCheck()
    },
    reset() {
      this.$refs.tree.setCheckedKeys([])
      this.handleNodeCheck()
    },
    filterNode(value, data) {
      if (!value) return true
      return data.name.indexOf(value) !== -1
    },
    /**
     * 节点状态改变
     */
    handleCheckClick(node, checked) {
      this.dealSelectAllChildrenTreeData(node, checked)
      this.currentIdList = this.$refs.tree.getCheckedKeys()
    },
    dealSelectAllChildrenTreeData(node, checked) {
      // 全部取消/选择
      const setChecked = (arr, ifChecked) => {
          arr?.map((item) => {
            this.$refs.tree.setChecked(item.id, ifChecked)
            if (item?.children?.length) {
              setChecked(item?.children, ifChecked)
            }
          })
      }
      // 如果为取消
      if (checked === false) {
        // 如果当前节点有子集
        // 循环子集将他们的选中取消
        setChecked(node?.children ?? [], false)
      } else {
        // 否则(为选中状态)
        // 判断父节点id是否为空
        if (node.parentId !== 'all') {
          // 如果不为空则将其选中
          // 循环子集将他们的选中取消
          setChecked(node?.children ?? [], true)
        }
      }
    }
  }
}
</script>

<style scoped>

</style>
